//
//  WmcSynchronousStatusView.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/2.
//

import UIKit

// MARK: - [RwaSynchronousStatusView]

class WmcSynchronousStatusView: UIView {
    // Lifecycle

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUI()
        self.makeConstraints()
        self.bindEvent()
        self.setDefaultStatus()
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    // Internal

    enum ColorStyle {
        case blue
        case white
    }

    var statusLabelColor: UIColor = .wmc_grayH8_8A8A99.withAlphaComponent(0.9)
    var clickClouser: (() -> Void)?

    var style: ColorStyle = .blue {
        didSet {
            if style == .blue {
                drawImageView.image = "cloud_upload_complete".wmc_image
                titleLabel.textColor = .wmc_grayH8_8A8A99
                if statusLabel.text != "同步失败" {
                    statusLabel.textColor = .wmc_grayH8_8A8A99
                }
                progressView.set(colors: .wmc_mainTheme)
                statusLabelColor = .wmc_grayH8_8A8A99.withAlphaComponent(0.9)
            } else if style == .white {
                drawImageView.image = "cloud_upload_complete".wmc_image.yp.set(tintColor: UIColor.white)
                titleLabel.textColor = .wmc_white_FFFFFF
                if statusLabel.text != "同步失败" {
                    statusLabel.textColor = .wmc_white_FFFFFF.withAlphaComponent(0.9)
                }
                progressView.set(colors: .wmc_white_FFFFFF)
                statusLabelColor = .wmc_white_FFFFFF.withAlphaComponent(0.9)
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.setupUI()
        self.makeConstraints()
        self.bindEvent()
        self.setDefaultStatus()
    }

    func updateProgress(_ progress: Double) {
        progressView.angle = Double(progress)
    }

    func setDefaultStatus() {
        if uploading {
            return
        }

        imageView.snp.updateConstraints { make in
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }

        imageView.isHidden = false
        progressView.isHidden = true
        warningImageView.isHidden = true
        drawImageView.isHidden = true
        statusLabel.textColor = self.statusLabelColor

        if WmcLoginManager.shared.isLogin {
            WmcPreferenceSettingsManager.fetchTeamSyncCount { [weak self] count in
                guard let weakSelf = self else { return }
                if count > 0 {
                    weakSelf.statusLabel.text = ""
                } else {
                    weakSelf.statusLabel.text = "未开启同步"
                }
            }
            
            statusLabel.isHidden = false
        } else {
            statusLabel.isHidden = true
        }
    }
    
    func setRedPointDisplay(_ display: Bool) {
        redPointView.isHidden = !display
    }

    // Private

    private lazy var statusBgView: UIView = {
        let view = UIView()
        return view
    }()

    private lazy var imageView: UIImageView = {
        let view = UIImageView()
        view.image = "team_alubm_icon".wmc_image
        view.contentMode = .scaleAspectFit
        return view
    }()

    private lazy var progressView: WmcCircleProgressView = {
        let view = WmcCircleProgressView()
        view.startAngle = -90
//        view.progressThickness = 0.3
//        view.trackThickness = 0
        view.clockwise = true
        view.gradientRotateSpeed = 2
        view.roundedCorners = true
        view.glowMode = .noGlow
        view.glowAmount = 0.9
        view.set(colors: .wmc_mainTheme)
        view.trackColor = .clear
        return view
    }()

    private lazy var redPointView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_red_F54A45
        view.layer.cornerRadius = 5
        view.layer.masksToBounds = true
        view.isHidden = true
        return view
    }()

    private lazy var warningImageView: UIImageView = {
        let view = UIImageView()
        view.image = "warning_icon".wmc_image
        view.isHidden = true
        return view
    }()

    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "团队相册"
        label.font = 12.yp.uiFont(weight: .medium)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()

    private lazy var statusLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 11)
        label.textAlignment = .center
        label.textColor = .wmc_grayH8_8A8A99.withAlphaComponent(0.9)
        label.minimumScaleFactor = 0.5
        label.adjustsFontSizeToFitWidth = true
        return label
    }()

    private lazy var drawImageView: UIImageView = {
        let view = UIImageView(image: "upload_complete_icon".wmc_image)
        view.isHidden = true
        return view
    }()

    private var uploading = false

    private func setupUI() {
        addSubview(statusBgView)
        statusBgView.addSubview(progressView)
        statusBgView.addSubview(imageView)
        statusBgView.addSubview(drawImageView)
        addSubview(warningImageView)
        addSubview(redPointView)
        addSubview(titleLabel)
        addSubview(statusLabel)
    }

    private func makeConstraints() {
        statusBgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.width.equalTo(50)
            make.height.equalTo(36)
        }

        progressView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(-5)
            make.bottom.equalTo(5)
        }

        imageView.snp.makeConstraints { make in
            make.top.left.equalTo(0.5)
            make.bottom.right.equalTo(-0.5)
        }

        drawImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(18)
            make.height.equalTo(13)
        }

        warningImageView.snp.makeConstraints { make in
            make.top.equalTo(-5)
            make.right.equalTo(-3)
            make.width.height.equalTo(18)
        }

        redPointView.snp.makeConstraints { make in
            make.top.equalTo(-2)
            make.right.equalTo(-6)
            make.width.height.equalTo(8)
        }

        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(statusBgView.snp.bottom).offset(7)
            make.left.right.equalToSuperview()
            make.height.equalTo(17)
        }

        statusLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(4)
        }
    }

    private func bindEvent() {
        WmcUploadQueueManager.shared.startSubject.subscribe { [weak self]  _ in
            guard let weakSelf = self else { return }
            weakSelf.imageView.snp.updateConstraints { make in
                make.top.equalTo(8)
                make.bottom.equalTo(-8)
            }
            weakSelf.progressView.isHidden = false
            weakSelf.statusLabel.textColor = weakSelf.statusLabelColor
            weakSelf.statusLabel.text = "同步中"
            weakSelf.statusLabel.isHidden = false
            weakSelf.uploading = true
            weakSelf.redPointView.isHidden = true
            weakSelf.transitionAnimation(style: .fromTop)
        }.disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.progressSubject.subscribe(onNext: { [weak self] progress in
            guard let weakSelf = self else { return }
            weakSelf.progressView.angle = progress * 360
            weakSelf.progressView.isHidden = false
            weakSelf.redPointView.isHidden = true
        }).disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.completionSubject.subscribe { [weak self] _ in
            guard let weakSelf = self else { return }
            WmcLogManager.Log("上传完成！")
            weakSelf.imageView.isHidden = true
            weakSelf.drawImageView.isHidden = false
            weakSelf.statusLabel.text = "同步成功"
            weakSelf.progressView.angle = 360
            weakSelf.progressView.isHidden = false

            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
                guard let weakSelf = self else { return }
                if !weakSelf.uploading {
                    weakSelf.setDefaultStatus()
                }
                weakSelf.transitionAnimation(style: .fromBottom)
            }

            weakSelf.uploading = false

        }.disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.failureSubject.subscribe { [weak self] _ in
            guard let weakSelf = self else { return }
            WmcLogManager.Log("上传失败！")
            weakSelf.warningImageView.isHidden = false
            weakSelf.statusLabel.textColor = .wmc_red_F54A45
            weakSelf.statusLabel.text = "同步失败"
            weakSelf.progressView.isHidden = true

            weakSelf.imageView.snp.updateConstraints { make in
                make.top.equalTo(0)
                make.bottom.equalTo(0)
            }

            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
                guard let weakSelf = self else { return }
                if !weakSelf.uploading {
                    weakSelf.setDefaultStatus()
                }
                weakSelf.transitionAnimation(style: .fromBottom)
            }

            weakSelf.uploading = false

        }.disposed(by: rx.disposeBag)
        
        WmcUploadQueueManager.shared.cancelAllTasksSubject.subscribe { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.uploading = false
            weakSelf.setDefaultStatus()
        }.disposed(by: rx.disposeBag)

        let tap = UITapGestureRecognizer(target: self, action: #selector(onClickAction))
        self.addGestureRecognizer(tap)
    }

    func transitionAnimation(style: CATransitionSubtype) {
        let transitionAnimation = CATransition()
        transitionAnimation.type = .push
        transitionAnimation.subtype = style
        layer.add(transitionAnimation, forKey: nil)
    }
    
    @objc
    private func onClickAction() {
        clickClouser?()
    }
}
